const ajax = (method, url, data) => {
  const token = wx.getStorageSync('token');
  const isLogin = url.indexOf('login') !== -1;
  const header = {
    Authorization: `JWT ${token}`,
  };

  wx.showLoading({
    title: '',
  });
  return new Promise((resolve, reject) => {
    wx.request({
      header: isLogin ? {} : header,
      url: `https://api.kecc.ltd/api/v1${url}`,
      data: data,
      method: method,
      dataType: 'json',
      success: res => {
        wx.hideLoading();

        if (res.statusCode === 200) {
          return resolve(res.data);
        } else if (res.statusCode === 400) {

          wx.showToast({
            title: res.data.errors[0],
            icon: 'none'
          })
        } else if (res.statusCode === 401) {
          wx.showToast({
            title: res.data.errors[0],
            icon: 'none'
          })
          return reject(res)
        } else {
          // const error = res.data.errors ? res.data.errors[0] : res.data.error[0]
          wx.showToast({
            title: '请求失败',
            icon: 'none',
          });
          return reject(res);
        }
      },
      fail: e => {
        wx.hideLoading();

        wx.showToast({
          title: '请求出错',
          icon: 'none',
        });
        console.log(e, 'error');

      },
    });
  });
};

module.exports = { ajax };
